import React, {useState, useEffect, useRef} from 'react'
import { Button, Form, Input, Switch, TreeSelect, message, Upload  } from 'antd';
import { fetchCates , updateCate, fetchCateDetail} from '@a/cateLists'
import { useNavigate } from 'react-router-dom';
export default function index(props: {cateId: number}) {
  const navigate = useNavigate();
  const formRef = useRef();

  // 监听 cateId 请求修改分类详情数据
  useEffect(() => {
    fetchCateDetail(props.cateId).then(res => {
      if (res.data.code === 200) {
        // 设置表单初始值
        formRef.current.setFieldsValue(res.data.data);
        icon = res.data.data.icon;
      }
    })
  }, [props.cateId])
  // 请求已有分类 作为当前新增分类 父级分类选项
  const [cates, setCates] = useState<any[]>([{
    pid: -1,
    cateName: '顶层分类'
  }])
  const getchCates = () => {
    fetchCates().then(res => {
      if (res.data.code === 200) {
        setCates([
          ...cates,
          ...res.data.data.lists
        ])
      }
    })
  }
  useEffect(() => {
    getchCates();
  }, [])
  // 提交表单新增分类
  const submitCate = (values: any) => {
    updateCate({
      ...values,
      icon
    }).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          // 刷新
         navigate(0)
        })
      }
    })
    
  };
  let icon = ''
  // 文件上传状态改变
  const fileUploadChange = (info: { file: { status: string; response: { data: { url: string; }; }; }; }) => {
    if(info.file.status === 'done') {
      icon = info.file.response.data.url
    }
    
  }
  return (
    <Form
      ref={formRef}
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      onFinish={submitCate}
      autoComplete="off"
    >
      <Form.Item
        label="分类名"
        name="cateName"
        rules={[{ required: true, message: '分类名必填!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="使用启用"
        name="enable"
        valuePropName="checked"
      >
        <Switch checkedChildren="启用" unCheckedChildren="禁用"/>
      </Form.Item>
      <Form.Item
        label="父级分类"
        name="pid"
        rules={[{ required: true, message: '父级分类必填!' }]}
      >
        <TreeSelect 
          treeData={cates}
          fieldNames={{
            label: 'cateName',
            value: 'id',
            children: 'children'
          }}/>
      </Form.Item>
      <Form.Item
        label="分类图标"
      >
        <Upload
          name="file"
          action="/api/upload"
          onChange={fileUploadChange}
        >
          <Button>点击上传</Button>
        </Upload>
       <img src={icon} alt="" />
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          确定
        </Button>
      </Form.Item>
    </Form>
  )
}
